package com.frejoys.common.service;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.frejoys.common.config.ValueConfig;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.util.SmsUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云短信服务
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AliSmsService {

    private final ValueConfig valueConfig;

    public void sendSms(String phone, String msg) {
        Map<String, String> map = new HashMap<>();
        map.put("code", msg);
        msg = JSONUtil.toJsonStr(map);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(valueConfig.getAliSmsSignName())
                .setTemplateCode(valueConfig.getAliSmsTemplateCode())
                .setPhoneNumbers(phone)
                .setTemplateParam(msg);
        RuntimeOptions runtime = new RuntimeOptions();

        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse ssr = SmsUtil.client.sendSmsWithOptions(sendSmsRequest, runtime);
            if (!ssr.statusCode.equals(HttpStatus.success.getCode()) || !ssr.body.code.equals("OK")) {
                throw new GeneralException(HttpStatus.codeSendError);
            }
        } catch (Exception error) {
            // error.printStackTrace();
            log.error("阿里云短信异常：", error);
            throw new GeneralException(HttpStatus.codeSendError);
        }

    }

}
